#!/urs/bin/env python
# coding:utf-8

from django.shortcuts import render, get_object_or_404
from .models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# from django.views.generic import ListView
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_mail
from .models import Post, Comment
from taggit.models import Tag
from django.db.models import Count
from .forms import SearchForm
from haystack.query import SearchQuerySet


# def post_list(request):
#     posts = Post.published.all())
#     return render(request, 'blog/post/list.html', {'posts': posts}

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post,
                             status='published',
                             publish__year=year,
                             publish__month=month,
                             publish__day=day)
    # active评论列表
    comments = post.comments.filter(active=True)

    if request.method == 'POST':
        # 评论被提交
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # 创建评论对象，但不保存
            new_comment = comment_form.save(commit=False)
            # 分配当前的post给这个评论
            new_comment.post = post
            # 保存评论到数据库
            new_comment.save()
    else:
        comment_form = CommentForm()

    post_tags_ids = post.tags.values_list('id', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]

    return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments,
                                                     'comment_form': comment_form,
                                                     'similar_posts': similar_posts})


def post_share(request, post_id):
    # 通过id来检索post内容
    post = get_object_or_404(Post, id=post_id, status='published')
    # 在html模板中应用，显示是否发生成功
    sent = False

    if request.method == 'POST':
        # 表单已提交
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # 表单字段合法
            cd = form.cleaned_data
            post_url = request.build_absolute_uri(post.get_absolute_url())
            name = cd['name'].encode('utf-8')
            comments = cd['comments'].encode('utf-8')
            subject = '{} ({}) recommends you reading "{}'.format(name, cd['email'], post.title)
            message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, name, comments)
            send_mail(subject, message, 'awvs_pyx@163.com', [cd['to']])
            sent = True
    else:
        form = EmailPostForm()

    return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent})


def post_list(request, tag_slug=None):
    object_list = Post.published.all()
    tag = None

    if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        object_list = object_list.filter(tags__in=[tag])
    paginator = Paginator(object_list, 2)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request, 'blog/post/list.html', {'page': page, 'posts': posts, 'tag': tag})

# class PostListView(ListView):
#     queryset = Post.published.all()
#     context_object_name = "posts"
#     paginate_by = 3
#     template_name = "blog/post/list.html"

def post_search(request):
    form = SearchForm()
    if 'query' in request.GET:
        form = SearchForm(request.GET)
        if form.is_valid():
            cd = form.cleaned_data
            results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all()
            total_results = results.count()
            paginator = Paginator(results, 2)
            page = request.GET.get('page')
            try:
                posts = paginator.page(page)
            except PageNotAnInteger:
                posts = paginator.page(1)
            except EmptyPage:
                posts = paginator.page(paginator.num_pages)
        else:
            cd = {}
            results = SearchQuerySet().models(Post).all()
            total_results = results.count()
            # posts = {}
            # page = {}
            paginator = Paginator(results, 2)
            page = request.GET.get('page')
            try:
                posts = paginator.page(page)
            except PageNotAnInteger:
                posts = paginator.page(1)
            except EmptyPage:
                posts = paginator.page(paginator.num_pages)

    else:
        cd = {}
        results = {}
        total_results = {}
        posts = {}
        page = {}
    return render(request, 'blog/post/search.html', {'form': form,
                                                     'cd': cd,
                                                     'results': results,
                                                     'total_results': total_results,
                                                     'posts': posts,
                                                     'page': page
                                                     })

def about_me(request):
    return render(request, 'blog/post/about.html')